package com.farm.project.service.impl;

import com.farm.project.domain.Field;
import com.farm.project.domain.FieldRePtype;
import com.farm.project.domain.FieldReTtype;
import com.farm.project.domain.Project;
import com.farm.project.domain.Task;
import com.farm.core.time.TimeTool;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.farm.project.dao.FieldDaoInter;
import com.farm.project.dao.FieldRePtypeDaoInter;
import com.farm.project.dao.FieldReTtypeDaoInter;
import com.farm.project.dao.ProjectDaoInter;
import com.farm.project.dao.TaskDaoInter;
import com.farm.project.service.FieldServiceInter;
import com.farm.web.WebUtils;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：属性服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class FieldServiceImpl implements FieldServiceInter {
	@Resource
	private FieldDaoInter fieldDaoImpl;
	@Resource
	private FieldRePtypeDaoInter fieldreptypeDaoImpl;
	@Resource
	private FieldReTtypeDaoInter fieldrettypeDaoImpl;
	@Resource
	private TaskDaoInter taskDaoImpl;
	@Resource
	private ProjectDaoInter projectDaoImpl;
	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(FieldServiceImpl.class);

	@Override
	@Transactional
	public Field insertFieldEntity(Field entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		if (StringUtils.isBlank(entity.getUuid())) {
			entity.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
		}
		entity.setLivetime(TimeTool.getTimeDate14());
		return fieldDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public Field editFieldEntity(Field entity, LoginUser user) {
		Field entity2 = fieldDaoImpl.getEntity(entity.getId());
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setSingletype(entity.getSingletype());
		entity2.setSort(entity.getSort());
		entity2.setValtype(entity.getValtype());
		entity2.setLivetime(TimeTool.getTimeDate14());
		entity2.setName(entity.getName());
		entity2.setPcontent(entity.getPcontent());
		entity2.setPstate(entity.getPstate());
		fieldDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteFieldEntity(String id, LoginUser user) {
		fieldreptypeDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("FIELDID", id, "=")).toList());
		fieldrettypeDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("FIELDID", id, "=")).toList());
		fieldDaoImpl.deleteEntity(fieldDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public Field getFieldEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return fieldDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createFieldSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "PLOGS_FIELD a left join PLOGS_FIELD_TYPE b on a.TYPEID=b.ID",
				"a.ID as ID,a.SINGLETYPE as SINGLETYPE,a.UUID as UUID,a.SORT as SORT,a.VALTYPE as VALTYPE,a.LIVETIME as LIVETIME,a.TYPEID as TYPEID,a.NAME as NAME,a.PCONTENT as PCONTENT,a.PSTATE as PSTATE,b.name as TYPENAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public void moveType(String fields, String typeid, LoginUser currentUser) {
		for (String fieldId : WebUtils.parseIds(fields)) {
			Field field = fieldDaoImpl.getEntity(fieldId);
			field.setTypeid(typeid);
			fieldDaoImpl.editEntity(field);
		}
	}

	@Override
	@Transactional
	public void loadSysField(String typeid, LoginUser currentUser) {
		// 创建系统默认分类
		List<String[]> paras = new ArrayList<>();
		// ------(new String[] {'公開類型','值類型','名稱','枚舉項','uuid','唯一性'});
		paras.add(new String[] { "1", "5", "签订合同", "1:是,0:否", "BOOKIS", "1" });
		paras.add(new String[] { "1", "5", "完成回款", "1:是,0:否", "PAYIS", "1" });
		paras.add(new String[] { "1", "5", "已开发票", "1:是,0:否", "BILLIS", "1" });
		paras.add(new String[] { "1", "5", "完成部署", "1:是,0:否", "BUILDIS", "1" });
		paras.add(new String[] { "1", "4", "合同金额", null, "BOOKPRICE", "1" });
		int sort = 10;
		for (String[] node : paras) {
			Field hasField = getFieldByUUID(node[4]);
			if (hasField == null) {
				Field field = new Field();
				field.setName(node[2]);
				field.setUuid(node[4]);
				field.setTypeid(typeid);
				field.setSort(++sort);
				field.setPstate("1");
				field.setSingletype(node[5]);
				field.setValtype(node[1]);
				field.setEnums(node[3]);
				insertFieldEntity(field, currentUser);
			} else {
				hasField.setName(node[2]);
				hasField.setUuid(node[4]);
				hasField.setTypeid(typeid);
				hasField.setSort(++sort);
				hasField.setPstate("1");
				hasField.setSingletype(node[5]);
				hasField.setValtype(node[1]);
				hasField.setEnums(node[3]);
				editFieldEntity(hasField, currentUser);
			}
		}
	}

	@Override
	@Transactional
	public Field getFieldByUUID(String uuid) {
		List<Field> fields = fieldDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("UUID", uuid, "=")).toList());
		if (fields.size() > 0) {
			return fields.get(0);
		} else {
			return null;
		}
	}

	@Override
	@Transactional
	public void editSort(String fieldid, int sort, LoginUser currentUser) {
		Field entity2 = fieldDaoImpl.getEntity(fieldid);
		entity2.setSort(sort);
		fieldDaoImpl.editEntity(entity2);
	}

	@Override
	@Transactional
	public boolean isEditByTask(String uuid, String taskId) {
		Field field = getFieldByUUID(uuid);
		if (field == null) {
			return true;
		}
		Task task = taskDaoImpl.getEntity(taskId);
		if (task == null) {
			return true;
		}
		Project project = projectDaoImpl.getEntity(task.getProjectid());
		List<FieldReTtype> reTtypes = fieldrettypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TASKTYPEID", task.getTasktypeid(), "="))
						.add(new DBRule("FIELDID", field.getId(), "=")).toList());
		if (reTtypes.size() > 0) {
			return reTtypes.get(0).getWriteis().equals("1");
		}
		List<FieldRePtype> rePtypes = fieldreptypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTTYPEID", project.getTypeid(), "="))
						.add(new DBRule("FIELDID", field.getId(), "=")).toList());
		if (rePtypes.size() > 0) {
			return rePtypes.get(0).getWriteis().equals("1");
		}
		return true;
	}

	@Override
	@Transactional
	public boolean isReadByTask(String uuid, String taskId) {
		Field field = getFieldByUUID(uuid);
		if (field == null) {
			return false;
		}
		Task task = taskDaoImpl.getEntity(taskId);
		if (task == null) {
			return false;
		}
		Project project = projectDaoImpl.getEntity(task.getProjectid());
		List<FieldReTtype> reTtypes = fieldrettypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TASKTYPEID", task.getTasktypeid(), "="))
						.add(new DBRule("FIELDID", field.getId(), "=")).toList());
		if (reTtypes.size() > 0) {
			return true;
		}
		List<FieldRePtype> rePtypes = fieldreptypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTTYPEID", project.getTypeid(), "="))
						.add(new DBRule("FIELDID", field.getId(), "=")).toList());
		if (rePtypes.size() > 0) {
			return rePtypes.get(0).getReadis().equals("1");
		}
		return true;
	}

}
